<?php

namespace app\admin\model\order;

use app\admin\model\goods\Goods;
use think\Db;
use think\Exception;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'spell_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'payTime_text',
        'pttime_text',
        'delivertime_text',
        'canceltime_text',
        'backtime_text',
        'finishtime_text'
    ];


    public function __construct($data = [])
    {
        parent::__construct($data);
//        $this->model=Db::table('pt_spell_order');
        $this->spellModel=new Spell();
    }

    public function getSkuPrice($goods,$model){
        $totalPrice=0;
        if($model==1 || $model==3) {
            foreach ($goods as $row) {
                $price = Db::table('pt_goods_skudetail')->where(['goodsId' => $row['goodsId'], 'skuId' => $row['skuId']])->value('price');
                if($model==3){
                    $price=Goods::where('goodsid',$row['goodsId'])->value('price');
                    if ($price <= 0 || $row['quantity'] <= 0 || $row['quantity']>5) return false;
                }
                $totalPrice = bcadd($totalPrice, bcmul($price, $row['quantity']>=1?intval($row['quantity']):1, 2), 2);
            }
        }elseif ($model==2){
            foreach ($goods as $row) {
                $discount=Goods::where(['goodsId'=>$row['goodsId']])->value('discount');
                $price = Db::table('pt_goods_skudetail')->where(['goodsId' => $row['goodsId'], 'skuId' => $row['skuId']])->value('price');
                if ($price <= 0 || $row['quantity'] <= 0) return false;
                $row['quantity'] = $row['quantity']>=1?intval($row['quantity']):1;
                $price=bcmul($price, $discount * 0.01, 2);
                $totalPrice = bcadd($totalPrice, bcmul($price, $row['quantity'], 2), 2);
            }
        }
        return $totalPrice;
    }


    public function dealSpellOrder($orderInfo){
        $pOrder=$this->spellModel->where([''=>$orderInfo['pOrderId']])->find();
        if(empty($pOrder)) return false;
        if($pOrder['balance']<=$orderInfo['price']){
            $pOrder['spellGroup'].=$orderInfo['spellGroup'].',';
            $data=[
                'spellGroup'=>$pOrder['spellGroup'],
                'balance'=>0,
                'isFinished'=>1,
                'finishTime'=>time()
            ];
            $this->save($data,['orderId'=>$pOrder['orderId']]);
            return true;
        }
        $totalPrice=$orderInfo['price'];
        $cOrders=$this->where(['pOrderId'=>$pOrder['orderId'],'isPaid'=>1])->select();
        foreach ($cOrders as $row){
            $totalPrice=bcadd($totalPrice,$row['price'],2);
        }
        if($pOrder['balance']<=$totalPrice) {
            $pOrder['spellGroup'].=$orderInfo['spellGroup'].',';
            $data=[
                'spellGroup'=>$pOrder['spellGroup'],
                'balance'=>0,
                'isFinished'=>1,
                'finishTime'=>time()
            ];
            $this->save($data,['orderId'=>$pOrder['orderId']]);
            return true;

        }else{
            $balance=bcsub($pOrder['balance'],$orderInfo['price'],2);
            $this->save(['balance'=>$balance],['orderId'=>$pOrder['orderId']]);
            return true;
        }
    }
    public function saveOrderdetail($uid,$orderId,$goods,$model=1){
        foreach ($goods as $row) {
            $skuInfo=Db::table('pt_goods_skudetail')->where(['goodsId'=>$row['goodsId'],'skuId' => $row['skuId']])->find();
            $goodsInfo=Db::table('pt_goods')->where(['goodsId' => $row['goodsId']])->find();
            if(empty($skuInfo)) break;
            $row['uid']=$uid;
            $row['orderId']=$orderId;
            $row['createtime']=time();
            $price=$skuInfo['price'];
            $row['quantity'] = $row['quantity']>=1?intval($row['quantity']):1;
            $row['price']=bcmul($price,$row['quantity'],2);
            if($model==2){
                $row['price']=bcmul($row['price'],$goodsInfo['discount']*0.01,2);
            }
            $row['goodsName']=$goodsInfo['title'];
            $row['skuName']=$skuInfo['title'];
            $row['image']=$skuInfo['image']?$skuInfo['image']:$goodsInfo['image'];
            Db::table('pt_spell_detail')->insert($row);
        }
        return true;
    }

    /**
     * @Explain :余额支付
     * @param $orderInfo
     * @param $userInfo
     * @Date : 2020/9/10 18:21
     * @Author : 河南邦耀网络科技有限公司
     * @throws Exception
     */
    public function balancePay($orderInfo,$userInfo){
        Db::startTrans();
        try {
            if ($userInfo->money >= $orderInfo['price']) {
                $this->save(['isPaid' => 1, 'payTime' => time()], ['orderId' => $orderInfo['orderId']]);
                $userInfo->money = bcsub($userInfo->money, $orderInfo['price']);
                $userInfo->save();
            }else{
                throw new Exception('余额不足');
            }
            Db::commit();
            return true;
        }catch (Exception$exception){
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * @Explain :订单检测
     * @Date : 2020/9/11 10:52
     * @Author : 河南邦耀网络科技有限公司
     */
    public function checkParentOrder($order){
        if(empty($order['ptid'])){
            return true;
        }
        $pOrder=$this->spellModel->where(['ptid'=>$order['ptid'],'start'=>1])->find();
        if(empty($pOrder)) {
            \app\admin\model\user\Spell::spellFail($order,"拼团信息获取失败");
            throw new Exception('拼团信息获取失败');
        }
        if($pOrder['isFinished'] != 0){
            \app\admin\model\user\Spell::spellFail($order,"此团已结束，请重新参团");
            throw new Exception('此团已结束，请重新参团');
        }
        $oldOrder=$this->spellModel->where(['uid'=>$order['uid'],'ptid'=>$order['ptid']])->find();
        if(!empty($oldOrder)) {
            \app\admin\model\user\Spell::spellFail($order,"您已参与该团");
            throw new Exception( '您已参与该团！');
        }
        //参此团的订单金额是否已超过剩余金额
        /*$sumPrice = \app\admin\model\SpellOrder::where('ptid',$order['ptid'])->where('payStatus',0)->where('orderStatus',1)->sum('payPrice');
        if($sumPrice>=$pOrder['balance']){
            \app\admin\model\user\Spell::spellFail($order,"参团人数已满，或请稍后重试");
            throw new Exception("参团人数已满，或请稍后重试");
        }*/
        return true;
    }




    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payTime']) ? $data['payTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pttime']) ? $data['pttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDelivertimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivertime']) ? $data['delivertime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getBacktimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['backtime']) ? $data['backtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finishtime']) ? $data['finishtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDelivertimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setBacktimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFinishtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
